package com.n5x.service.impl;

import com.n5x.mapper.admin.AdminUserMapper;
import com.n5x.model.AbstractModel;
import com.n5x.model.admin.AdminUser;
import com.n5x.model.admin.AdminUserExample;
import com.n5x.model.user.UserAccount;
import com.n5x.service.IAdminService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Administrator on 2017/9/22.
 */
@Service
@Transactional
public class IAdminServiceImpl implements IAdminService {

    @Autowired
    private AdminUserMapper adminUserMapper;

    public AdminUser saveAdminUser(AdminUser adminUser) {
        adminUser.setLastUpdateTime(new Date());
        if (StringUtils.isNotBlank(adminUser.getId())) {
            adminUserMapper.updateByPrimaryKeySelective(adminUser);
        } else {
            adminUser.init();
            adminUserMapper.insert(adminUser);
        }
        return adminUser;
    }

    public List<AdminUser> findAdminUserList(AdminUserExample.Criteria criteria) {
        AdminUserExample adminUserExample = new AdminUserExample();
        if (criteria == null) {
            criteria = adminUserExample.or();
        } else {
            adminUserExample.or(criteria);
        }
        adminUserExample.setOrderByClause(AbstractModel.ORDER);
        return adminUserMapper.selectByExample(adminUserExample);
    }

    public AdminUser findAdminUser(String id) {
        return adminUserMapper.selectByPrimaryKey(id);
    }

    public AdminUser cheackUserByAccount(String login, String pwd) {
        Assert.notNull(login, "登陆名称不能为空");
        Assert.notNull(pwd, "登陆密码不能为空");
        AdminUserExample adminUserExample = new AdminUserExample();
        pwd = AdminUser.encodePassword(pwd);
        adminUserExample.or().andLoginNameEqualTo(login).andDisableEqualTo(Boolean.FALSE).andPasswordEqualTo(pwd);
        Iterator<AdminUser> adminUserIterator = adminUserMapper.selectByExample(adminUserExample).iterator();
        if (adminUserIterator.hasNext()) {
            return adminUserIterator.next();
        }
        return null;
    }
}
